package com.nCoV.EpidemicSurveillance.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	private boolean postOnly = true;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    	if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}

    	if(request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
    		String username = null;
    		String password = null;
    		try {
				@SuppressWarnings("unchecked")
				Map<String, Object> map = new ObjectMapper().readValue(request.getInputStream(),Map.class);
				username = map.get("username").toString();
				password = map.get("password").toString();
				if (username == null) {
					username = "";
				}

				if (password == null) {
					password = "";
				}
				username = username.trim();
				UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
						username, password);

				// Allow subclasses to set the "details" property
				setDetails(request, authRequest);


				return this.getAuthenticationManager().authenticate(authRequest);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
    	}
    	return super.attemptAuthentication(request, response);		
    }
}